<template>
    <div>
        <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
        <el-button type="success" :icon="CirclePlusFilled" @click="editCourseVisible = true"
                style="width:100%;margin-bottom: 8px">新增课程</el-button>
        <div class="container">
            
            <!-- Table -->
            <div class="table-container">

                <el-table v-loading="loading" :data="tableData" style="width: 100%" :stripe="true">
                    <el-table-column type="expand" align="center">
                        <template #default="props">
                            <el-button type="warning" :icon="CirclePlusFilled"
                                @click="editVisible = true; addTcCourse_id = props.row.course_id"
                                style="width:100%">新增教学班</el-button>
                            <div class="card-container">
                                <el-card v-for="detail in props.row.teachClassList" :key="detail.teacher" class="cards"
                                    shadow="hover">

                                    <el-descriptions :column="2" :border="1" direction="vertical">
                                        <el-descriptions-item label="授课教师">{{ detail.teacher.name
                                            }}</el-descriptions-item>
                                        <el-descriptions-item label="上课学期">{{ detail.semester }}</el-descriptions-item>
                                        <el-descriptions-item label="周数">{{ detail.start_week }}-{{ detail.end_week
                                            }}</el-descriptions-item>
                                        <el-descriptions-item label="已选/容量">{{ detail.selected }}/{{ detail.capacity
                                            }}</el-descriptions-item>
                                    </el-descriptions>
                                    <div class="button-container">
                                        <el-button class="button" type="primary"
                                            @click="handleSession(detail.tc_id)">时间</el-button>
                                        <el-button type="primary" class="button"
                                            @click="handleStudentCourse(detail.tc_id)" size="mini">学生</el-button>
                                        <el-button type="primary" class="button" @click="handleEdit(detail)"
                                            size="mini">编辑</el-button>
                                        <el-button type="danger" class="button" @click="handleDeleteTeachClass(detail)"
                                            size="mini">删除</el-button>
                                    </div>
                                </el-card>
                            </div>
                        </template>
                    </el-table-column>
                    <!-- 表头项 -->
                    <el-table-column align="center" label="课程编号" prop="course_id" />
                    <el-table-column align="center" label="课程名" prop="name" />
                    <el-table-column align="center" label="简介" prop="description" />
                    <el-table-column align="center" label="学院" prop="college.name" />
                    <el-table-column align="center" label="学分" prop="credit" />
                    <el-table-column align="center" label="操作" prop="opts">
                        <template #default="{ row, column, $index }">
                            <el-button type="primary" @click="handleCourseEdit(row)" size="mini">编辑</el-button>
                            <el-button type="danger" @click="handleDeleteCourse(row)" size="mini">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-dialog v-model="studentCourseVisible" title="班级管理">
                <TableCustom :columns="scColumns" :tableData="studentCourseList" :total="studentCourseList.length">
                    <template #grade="{ rows, index }">
                        <el-input v-model="rows.grade" size="mini" style="width: 100px" placeholder="请输入成绩" />
                    </template>
                    <template #scopt="{ rows, index }">
                        <el-button type="primary" @click="updateGrade(rows)" size="mini">更新成绩</el-button>
                        <el-button type="danger" @click="deleteStudent(rows)" size="mini">取消课程</el-button>
                    </template>
                </TableCustom>
            </el-dialog>
            <Sessions :visible="sessionVisible" :sessionList="sessionList"
                :handle-close="() => { sessionVisible = false }" :tc_id="sessionTcId" />

            <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="editVisible" width="700px" destroy-on-close
                :close-on-click-modal="false" @close="closeEditDialog">
                <TableEdit :form-data="rowData" :options="tcOptions" :edit="isEdit" :update="editOk">
                </TableEdit>
            </el-dialog>

            <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="editCourseVisible" width="700px" destroy-on-close
                :close-on-click-modal="false" @close="closeEditCourseDialog">
                <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="editCourseOk">
                </TableEdit>
            </el-dialog>

            <!-- Pagination -->
            <div class="pagination-container">
                <el-pagination background layout="total,prev, pager, next" @current-change="changePage"
                    :total="page.total" :index="page.index" :page-size="page.size" />
            </div>
        </div>
    </div>
</template>




<script lang="ts" setup>

import { ref, reactive } from 'vue';
import { ElMessage, } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { fetchCoursePage, fetchSessionByTcId, selectTeachClass, fetchStudentCourse, updateStudentCourse, deleteStudentCourse, updateTeachClass, insertTeachClass, insertCourse, deleteCourse, updateCourse, deleteTeachClass } from '@/api/index';
import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import TableSearch from '@/components/table-search.vue';
import { TableItem } from '@/types/table';
import { FormOption, FormOptionList } from '@/types/form-option';

// 查询相关
const query = reactive({
	name: null,
	course_id: null,
	college_id: null
});
const searchOpt = ref<FormOptionList[]>([
	{ type: 'input', label: '课程名：', prop: 'name' },
	{ type: 'number', label: '课程号', prop: 'course_id' },
	{ type: 'number', label: '学院号', prop: 'college_id' }
])
const handleSearch = () => {
    getData();
};
const page = reactive({
    index: 1,
    size: 10,
    total: 200,
})
const loading = ref(true);

const sessionList = ref([]);
const sessionVisible = ref(false);
const sessionTcId = ref(0);
const handleSession = async (tc_id) => {
    let res = await fetchSessionByTcId(tc_id)
    sessionVisible.value = true;
    sessionList.value = res.data;
    sessionTcId.value = tc_id;
};

//学生管理
const studentCourseInfo = [
    { prop: "student.name", label: '姓名' },
    { prop: "student.sid", label: '学号' },
    { prop: "grade", label: '成绩' },
]
let scColumns = ref([
    { type: 'index', label: '序号', width: 55, align: 'center' },
    ...studentCourseInfo,
    { prop: 'scopt', label: '操作', width: 250 }
])
const studentCourseList = ref([]);
const studentCourseVisible = ref(false);
const handleStudentCourse = async (tc_id) => {
    let res = await fetchStudentCourse({ index: 1, size: 100000, tc_id: tc_id })
    studentCourseVisible.value = true;
    studentCourseList.value = res.data.pageList;
};
//课程编辑
let options = ref<FormOption>({
    labelWidth: '100px',
    span: 24,
    list: [
        { type: 'input', label: '课程名', prop: 'name', required: true },
        { type: 'input', label: '简介', prop: 'description', required: true },
        { type: 'input', label: '学分', prop: 'credit', required: true },
        { type: 'input', label: '学院id', prop: 'college_id', required: true },
    ]
})
let editCourseVisible = ref(false);
const handleCourseEdit = (row) => {
    rowData.value = { ...row };
    isEdit.value = true;
    editCourseVisible.value = true;
};
const handleDeleteCourse = (row) => {
    deleteCourse(row.course_id).then(() => {
        getData();
        ElMessage.success('删除成功');
    },
        () => {
            ElMessage.error('删除失败');
        })

}
const closeEditCourseDialog = () => {
    editCourseVisible.value = false;
    isEdit.value = false;
};
const insertCourseData = (data) => {
    closeEditCourseDialog();
    insertCourse(data).then(() => {
        getData();
        ElMessage.success('新增成功');
    }).catch(() => {
        ElMessage.error('新增失败');
    })
}
const updateCourseData = (data) => {
    closeEditCourseDialog();
    updateCourse(data).then(() => {
        getData();
        ElMessage.success('更新成功');
    }).catch(() => {
        ElMessage.error('更新失败');
    })
}
const editCourseOk = (data) => {
    if (isEdit.value) {
        updateCourseData(data)
    } else {
        insertCourseData(data)
    }
}
//教学班编辑
// 新增/编辑弹窗相关
let tcOptions = ref<FormOption>({
    labelWidth: '100px',
    span: 24,
    list: [
        { type: 'number', label: '教师号', prop: 'teacher_id', required: true },
        { type: 'number', prop: 'start_week', label: '开始周', required: true },
        { type: 'number', prop: 'end_week', label: '结束周', required: true },
        { type: 'input', label: '上课学期', prop: 'semester', required: true },
        { type: 'number', prop: 'capacity', label: '容量', required: true },
    ]
})
const editVisible = ref(false);
const addTcCourse_id = ref(0);
const isEdit = ref(false);
const rowData = ref({});
const handleEdit = (row) => {
    rowData.value = { ...row };
    rowData.value.teacher_id = row.teacher.teacher_id;
    console.log(rowData)
    isEdit.value = true;
    editVisible.value = true;
};
const closeEditDialog = () => {
    editVisible.value = false;
    isEdit.value = false;
};
const handleDeleteTeachClass = (row) => {
    deleteTeachClass(row.tc_id).then(() => {
        getData();
        ElMessage.success('删除成功');
    },
        () => {
            ElMessage.error('删除失败');
        })
}
const insertData = (data) => {
    closeEditDialog();
    insertTeachClass(data).then(() => {
        getData();
        ElMessage.success('新增成功');
    },
        () => {
            ElMessage.error('新增失败');
        })
}
const updateData = (data) => {
    closeEditDialog();
    updateTeachClass(data).then(() => {
        getData();
        ElMessage.success('更新成功');
    },
        () => {
            ElMessage.error('更新失败');
        })
}
const editOk = (data) => {
    data.college = {}
    data.college.college_id = data.college_id;
    data.course_id = addTcCourse_id.value;
    if (isEdit.value) {
        updateData(data)
    } else {
        insertData(data)
    }
}

//页面
const changePage = async (val: number) => {
    loading.value = true;
    const res = await fetchCoursePage({ index: val, size: page.size }, query)
    res.data.pageList.forEach(item => {

        if (item.college) item.college_id = item.college.college_id
    })
    tableData.value = res.data.pageList;
    console.log(tableData)
    page.total = res.data.pageNumber;
    page.index = val;
    loading.value = false;
    console.log(tableData)
};

const tableData = ref<[]>([]);
const getData = async () => {
    changePage(page.index)
};
getData();


const updateGrade = async (rows) => {
    updateStudentCourse(rows).then((data) => {
        ElMessage.success(data.data);
    }).catch((err) => {
        ElMessage.error(err.response.data);
    })
    console.log(rows)
}
const deleteStudent = async (row) => {
    console.log(row)
    deleteStudentCourse({ tc_id: row.teachClass.tc_id, sid: row.student.sid }).then((data) => {
        ElMessage.success(data.data);
        handleStudentCourse(row.teachClass.tc_id);

    }).catch((err) => {
        ElMessage.error(err.response.data);
    })
}

</script>

<style scoped>
.pagination-container {
    margin-top: 20px;
    /* Adjust as needed */
}

.card-container {
    display: flex;
    flex-wrap: wrap;
    /* 确保子项超过四个时能自动换行 */
    justify-content: flex-start;
    /* 对齐方式 */
}

.cards {
    margin: 8px;
    flex-basis: calc(25% - 20px);
    max-width: calc(25% - 20px);
}

.cards p {
    padding-left: 20px;
}

.button-container {
    display: flex;
    justify-content: center;
}

.cards .button {
    margin-top: 8px;
    /*margin horizontal center*/
    flex-grow: 1;
}
</style>